import axios from 'axios'
import {
	getStore,
	setStore
} from './storage';
// import {
// 	router
// } from '../router/index';
import {
	Message
} from 'view-design';
import { getToken } from './utils';
// 超时设定
axios.defaults.timeout = 30000;

axios.interceptors.request.use(config => {
	return config;
}, err => {
	Message.error('请求超时');
	return Promise.resolve(err);
});
class HttpRequest {
	constructor(baseUrl) {
		this.baseUrl = baseUrl
		this.queue = {}
	}
	getInsideConfig() {
		let accessToken = getToken('accessToken');
		return {
			baseURL: this.baseUrl,
			headers: {
				'accessToken': accessToken,
				'Content-Type': 'application/x-www-form-urlencoded',
			},
			transformRequest: [function (data) {
				let ret = '';
				for (let it in data) {
					ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
				}
				ret = ret.substring(0, ret.length - 1);
				return ret;
			}],
		}
	}
	destroy(url) {
		delete this.queue[url]
	}
	interceptors(instance, url) {
		// 请求拦截
		instance.interceptors.request.use(
			config => {
				this.queue[url] = true
				// console.log('config:',config)
				return config
			},
			error => {
				return Promise.reject(error)
			}
		)
		instance.interceptors.response.use(
			res => {
				this.destroy(url)
				const { data, status } = res
				return { data, status }
			},
			error => {
				this.destroy(url)
				return Promise.reject(error)
			}
		)
	}
	request(options) {
		const instance = axios.create()
		// console.log('instance',instance);
		options = Object.assign(this.getInsideConfig(), options)
		this.interceptors(instance, options.url)
		// console.log('options',options)
		return instance(options)
	}
}
export default HttpRequest